import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { RoleDept } from './entities/role-dept.entity';

@Injectable()
export class RoleDeptService {
  constructor(
    @InjectRepository(RoleDept)
    private readonly roleDept: Repository<RoleDept>,
  ) {}

  findAll(role_id: number) {
    return this.roleDept.find({
      where: {
        role_id,
      },
    });
  }

  insert(insertRows: any[]) {
    return this.roleDept.insert(insertRows);
  }

  /**
   * 修改角色部门关联（新增、修改、删除）
   * @param deptIds //部门数组
   * @param roleId  //角色ID
   */
  async updateRoleDept(deptIds: number[], roleId: number) {
    try {
      return await this.roleDept.manager.transaction(async (manager) => {
        // 查找表中的角色菜单
        const roleDepts = await manager.find(RoleDept, {
          where: { role_id: roleId },
        });

        // 在deptIds中找出roleDepts所没有的,新增表中没有的角色菜单
        let insertRows = deptIds.filter(
          (k) => !roleDepts.some((j) => j.role_id == roleId && j.dept_id == k),
        );
        if (insertRows && insertRows.length > 0) {
          await manager.insert(
            RoleDept,
            insertRows.map((m) => {
              return {
                role_id: roleId,
                dept_id: m,
              };
            }),
          );
        }

        // 在roleDepts中找出deptIds所没有的，删除表中没有roleDepts的角色菜单
        let deleteRows = roleDepts.filter(
          (k) => !deptIds.some((j) => j == k.dept_id),
        );
        if (deleteRows && deleteRows.length > 0) {
          await manager.delete(RoleDept, {
            role_id: roleId,
            dept_id: In(deleteRows.map((m) => m.dept_id)),
          });
        }
      });
    } catch (err) {
      return err;
    }
  }
}
